package md.lanjing.com.module_mine.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.lxh.baselibray.constant.ARouterConfig;
import com.lxh.baselibray.dialog.AlertDialog;
import com.lxh.baselibray.event.BusFactory;
import com.lxh.baselibray.mvp.MvpActivity;
import com.lxh.baselibray.util.BitmapUtils;
import com.lxh.baselibray.util.CameraUtils;
import com.lxh.baselibray.util.ObjectUtils;
import com.lxh.baselibray.util.RegexUtils;
import com.lxh.baselibray.util.SPUtils;
import com.lxh.baselibray.util.SizeUtils;
import com.lxh.baselibray.util.ToastUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;

import com.lxh.baselibray.constant.Constant;
import com.lxh.baselibray.event.EventImpl;

import md.lanjing.com.module_mine.R;
import md.lanjing.com.module_mine.R2;
import md.lanjing.com.module_mine.contact.RealNameAuthenContact;
import md.lanjing.com.module_mine.bean.RealNameAuthenticationResponse;
import retrofit2.Response;

/**
 * 实名认证
 */
@Route(path = ARouterConfig.Mine_real_name_authen_act)
public class RealNameAuthenticationActivity extends MvpActivity<RealNameAuthenContact.RealNameAuthenPresent> implements RealNameAuthenContact.IRealNameAuthenView {
    @BindView(R2.id.iv_take_person_pic)
    ImageView ivTakePersonPic;
    @BindView(R2.id.linear_takpe_person)
    LinearLayout linearTakpePerson;
    @BindView(R2.id.iv_take_emblem_pic)
    ImageView ivTakeEmblemPic;
    @BindView(R2.id.linear_take_emblem)
    LinearLayout linearTakeEmblem;
    @BindView(R2.id.btn_confirm)
    Button btnConfirm;

    RxPermissions rxPermissions;

    public static final int TAKE_PHOTO = 1;//启动相机标识
    public static final int SELECT_PHOTO = 2;//启动相册标识
    @BindView(R2.id.et_name)
    EditText etName;
    @BindView(R2.id.et_id_card)
    EditText etIdCard;

    private File outputImagepath;//存储拍完照后的图片

    private Bitmap orc_bitmap;//拍照和相册获取图片的Bitmap
    AlertDialog dialog = null;

    private String base64Front;
    private String base64Back;
    private int flag;

    String realName;
    @Override
    public void initData(Bundle savedInstanceState) {
        rxPermissions = new RxPermissions(this);

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_real_name_authentication;
    }


    @OnClick({R2.id.linear_takpe_person, R2.id.linear_take_emblem, R2.id.btn_confirm,R2.id.iv_take_person_pic,R2.id.iv_take_emblem_pic})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.linear_takpe_person || i == R.id.iv_take_person_pic) {
            flag = 1;
            showTakePhotoDialog();

        } else if (i == R.id.linear_take_emblem || i == R.id.iv_take_emblem_pic) {
            flag = 2;
            showTakePhotoDialog();

        } else if (i == R.id.btn_confirm) {
            realName = etName.getText().toString();
            String idNo = etIdCard.getText().toString();
            if (ObjectUtils.isEmpty(realName)) {
                ToastUtils.showLongToast(context, "请输入姓名");
                return;
            }
            if (ObjectUtils.isEmpty(idNo)) {
                ToastUtils.showLongToast(context, "请输入身份证号");
                return;
            }
            if (!RegexUtils.isIDCard18(idNo)) {
                ToastUtils.showLongToast(context, "请输入正确的身份证号");
                return;
            }
            if (ObjectUtils.isEmpty(base64Front)) {
                ToastUtils.showLongToast(context, "请拍摄正面照");
                return;
            }
            if (ObjectUtils.isEmpty(base64Back)) {
                ToastUtils.showLongToast(context, "请拍摄反面照");
                return;
            }
            showLoadingDialog();
            mPresent.realNameAuthen(context, base64Front, base64Back, realName, idNo);

        }
    }


    private void showTakePhotoDialog() {
        rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                                .addDefaultAnimation()
                                .setContentView(R.layout.dialog_take_photo)
                                .setWidthAndHeight(SizeUtils.dp2px(context, 228), SizeUtils.dp2px(context, 90))
                                .setCancelable(true)
                                .setOnClickListener(R.id.tv_take_photo, v -> {
                                    SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                                            "yyyy_MM_dd_HH_mm_ss");
                                    String filename = timeStampFormat.format(new Date());
                                    outputImagepath = new File(Environment.getExternalStorageDirectory(),
                                            filename + ".jpg");
                                    Intent takePhotoIntent = CameraUtils.getTakePhotoIntent(context, outputImagepath);
                                    startActivityForResult(takePhotoIntent, TAKE_PHOTO); // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
                                    dialog.dismiss();
                                }).setOnClickListener(R.id.tv_select_pic, v -> {
                                    dialog.dismiss();
                                    Intent selectPhotoIntent = CameraUtils.getSelectPhotoIntent();
                                    startActivityForResult(selectPhotoIntent, SELECT_PHOTO);
                                });
                        dialog = builder.create();
                        dialog.show();
                    } else {
                        ToastUtils.showLongToast(context, "权限未开启");
                    }
                });

    }

    /**
     * 拍完照和从相册获取玩图片都要执行的方法(根据图片路径显示图片)
     */
    private void displayImage(String imagePath, ImageView iv) {
        if (!TextUtils.isEmpty(imagePath)) {
            //orc_bitmap = BitmapFactory.decodeFile(imagePath);//获取图片
            orc_bitmap = CameraUtils.comp(BitmapFactory.decodeFile(imagePath)); //压缩图片
            if (flag == 1) {
                //正面
                base64Front = BitmapUtils.bitmapToBase64(orc_bitmap);
            } else if (flag == 2) {
                //反面
                base64Back = BitmapUtils.bitmapToBase64(orc_bitmap);
            }
            CameraUtils.ImgUpdateDirection(imagePath, orc_bitmap, iv);//显示图片,并且判断图片显示的方向,如果不正就放正
        } else {
            ToastUtils.showLongToast(context, "图片获取失败");
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //打开相机后返回
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    if (flag == 1) {

                        linearTakpePerson.setVisibility(View.GONE);
                        displayImage(outputImagepath.getAbsolutePath(), ivTakePersonPic);
                    } else if (flag == 2) {
                        linearTakeEmblem.setVisibility(View.GONE);
                        displayImage(outputImagepath.getAbsolutePath(), ivTakeEmblemPic);
                    }
                }
                break;
            //打开相册后返回
            case SELECT_PHOTO:
                if (resultCode == RESULT_OK) {
                    String imagePath = null;
                    //判断手机系统版本号
                    if (Build.VERSION.SDK_INT > 19) {
                        //4.4及以上系统使用这个方法处理图片
                        imagePath = CameraUtils.getImgeOnKitKatPath(data, context);
                    } else {
                        imagePath = CameraUtils.getImageBeforeKitKatPath(data, context);
                    }
                    if (flag == 1) {
                        linearTakpePerson.setVisibility(View.GONE);
                        displayImage(imagePath, ivTakePersonPic);
                    } else if (flag == 2) {
                        linearTakeEmblem.setVisibility(View.GONE);
                        displayImage(imagePath, ivTakeEmblemPic);
                    }

                }
                break;
            default:
                break;
        }
    }



    @Override
    public void getRealNameAuthenData(Response<RealNameAuthenticationResponse> response) {
        dismissLoadingDialog();
        if (response.body().getCode()== Constant.SUCCESS_CODE){
            ToastUtils.showLongToast(context,"实名认证成功");
            BusFactory.getBus().post(new EventImpl.RealEvent());
            SPUtils.putString(Constant.IS_REAL,realName,context);
            finish();
        }else {
            ToastUtils.showLongToast(context,response.body().getMsg());
        }
    }

    @Override
    protected RealNameAuthenContact.RealNameAuthenPresent createPresent() {
        return new RealNameAuthenContact.RealNameAuthenPresent();
    }
}
